<template>
  <a-card :bordered="false" style="width: 100%">
    <!-- 自定义顶部搜索 -->
    <template #title>
      <div style="display: flex">
        <a-row class="a-row-search" :gutter="16">
          <a-col :lg="8">
            <span>用户名称：</span>
            <a-input
              style="width: 200px"
              v-model:value="searchUser.username"
              placeholder="用户名称"
            ></a-input>
          </a-col>
          <a-col :lg="8">
            <span>手机号码：</span>
            <a-input
              style="width: 200px"
              v-model:value="searchUser.phone"
              placeholder="手机号码"
            ></a-input>
          </a-col>
          <a-col :lg="8">
            <span>用户状态：</span>
            <a-select
              placeholder="用户状态"
              ref="select"
              v-model:value="searchUser.status"
              style="width: 200px"
              @change="handleChange"
              :options="statusData"
            />
          </a-col>
        </a-row>
        <div
          style="
            width: 15%;
            display: flex;
            align-items: center;
            justify-content: flex-end;
          "
        >
          <a-space :size="40">
            <a-button
              type="primary"
              v-permission="`permission:user:query`"
              :loading="saveLoading"
              @click="handleSearch"
              >查询</a-button
            >
            <a-button
              @click="handleReset"
              v-permission="`permission:role:reset`"
              >重置</a-button
            >
          </a-space>
        </div>
      </div>
    </template>

    <!-- 用户表格数据 -->
    <a-table
      :scroll="{ x: 1300 }"
      :dataSource="tableData"
      :loading="loading"
      :pagination="false"
    >
      <a-table-column
        fixed="left"
        title="用户编号"
        dataIndex="id"
        :width="60"
      />
      <a-table-column
        fixed="left"
        title="用户名称"
        dataIndex="username"
        :width="80"
      />
      <a-table-column title="手机号" dataIndex="phone" :width="100" />
      <a-table-column title="邮箱" dataIndex="email" :width="130" />
      <a-table-column title="状态" dataIndex="status" :width="60">
        <template #default="{ record }">
          <a-switch
            v-model:checked="record.checked"
            @change="handleChangeStatus(record.id)"
          >
            <template #checkedChildren><check-outlined /></template>
            <template #unCheckedChildren><close-outlined /></template>
          </a-switch>
        </template>
      </a-table-column>
      <a-table-column title="创建时间" dataIndex="createTime" :width="120" />
      <a-table-column fixed="right" title="操作" :width="140">
        <template #default="{ record }">
          <a-button
            v-permission="`permission:user:update`"
            type="link"
            size="small"
            @click="handleEchoUser(record.id)"
          >
            <FormOutlined />
            修改
          </a-button>
          <a-popconfirm
            placement="bottom"
            ok-text="确认"
            cancel-text="取消"
            title="确认删除该用户？"
            @confirm="handleRemoveUser(record.id)"
          >
            <a-button
              type="link"
              danger
              size="small"
              v-permission="`permission:user:delete`"
            >
              <DeleteOutlined />
              删除
            </a-button>
          </a-popconfirm>
          <a-dropdown :trigger="['click']">
            <a-button
              type="link"
              size="small"
              v-permission="`permission:user:more`"
            >
              <DoubleRightOutlined />
              更多
            </a-button>
            <template #overlay>
              <a-menu>
                <a-menu-item key="0">
                  <a-button
                    v-permission="`permission:user:resetpwd`"
                    type="link"
                    size="small"
                    @click="handleResetPwdOpen(record.id)"
                  >
                    <KeyOutlined />
                    重置密码
                  </a-button>
                </a-menu-item>
                <a-menu-item key="1">
                  <a-button
                    type="link"
                    v-permission="`permission:user:assign`"
                    :loading="saveLoading"
                    size="small"
                    @click="handleRoleOpen(record)"
                  >
                    <SendOutlined spin />
                    分配角色
                  </a-button>
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </template>
      </a-table-column>
    </a-table>

    <!-- 分页 -->
    <div class="pagination-style">
      <a-pagination
        @change="handlePaginationChange"
        v-model:current="pageNo"
        v-model:pageSize="pageSize"
        :total="total"
      />
    </div>
  </a-card>

  <!-- 修改用户弹框 -->
  <a-modal
    @cancel="handlerCancel"
    v-model:open="updateUserOpen"
    width="30%"
    title="修改用户"
  >
    <a-form
      ref="formRef"
      :model="user"
      :rules="rules"
      :wrapper-col="wrapperCol"
      :labelCol="labelCol"
    >
      <a-form-item ref="username" label="用户名称" name="username">
        <a-input v-model:value="user.username" />
      </a-form-item>
      <a-form-item ref="phone" label="手机号" name="phone">
        <a-input v-model:value="user.phone" />
      </a-form-item>
      <a-form-item ref="email" label="邮箱" name="email">
        <a-input v-model:value="user.email" />
      </a-form-item>
    </a-form>

    <template #footer>
      <a-button
        key="submit"
        type="primary"
        :loading="saveLoading"
        @click="handleSaveUser"
        >确定</a-button
      >
      <a-button key="back" @click="handlerCancel">取消</a-button>
    </template>
  </a-modal>

  <!-- 重置密码弹框 -->
  <a-modal
    @cancel="handlerCancel"
    v-model:open="resetPwdOpen"
    width="30%"
    title="重置密码"
  >
    <a-form
      ref="formRef"
      :model="resetUserPwd"
      :rules="rules"
      :wrapper-col="wrapperCol"
      :labelCol="labelCol"
    >
      <a-form-item ref="password" label="新密码" name="password">
        <a-input-password v-model:value="resetUserPwd.password" />
      </a-form-item>
    </a-form>

    <template #footer>
      <a-button
        key="submit"
        type="primary"
        :loading="saveLoading"
        @click="handleResetPwd"
        >确定</a-button
      >
      <a-button key="back" @click="handlerCancel">取消</a-button>
    </template>
  </a-modal>

  <!--分配角色抽屉 -->
  <a-drawer
    :closable="false"
    :width="450"
    title="分配角色"
    :placement="placement"
    :open="drawerOpen"
    @close="onClose"
  >
    <template #extra>
      <a-button style="margin-right: 10px" @click="onClose">取消</a-button>
      <a-button type="primary" :loading="saveLoading" @click="handleRoleSave"
        >确定</a-button
      >
    </template>
    <div class="permisson-role">
      <span>用户分配：</span>
      <a-input
        v-model:value="tempUserName"
        disabled
        style="width: 260px; height: 33px"
      ></a-input>
    </div>
    <a-checkbox-group v-model:value="checkedRoles" style="width: 100%">
      <a-row :gutter="[16, 25]">
        <a-col :span="6" v-for="(item, index) in allRoles" :key="index">
          <a-checkbox :value="item">{{ item }}</a-checkbox>
        </a-col>
      </a-row>
    </a-checkbox-group>
  </a-drawer>
</template>

<script setup>
import { ref, onMounted } from "vue";
import {
  findUserList,
  updateUserStatus,
  queryEchoUserInfo,
  updateUserInfo,
  deleteUser,
  resetPwd,
  queryRoles,
  saveRoles,
} from "@/api/user";
import { message } from "ant-design-vue";
import { queryRoleNameList } from "@/api/role";
import { queryDictLabel } from "@/api/dict_data";
import { USER_CONSTANT } from "@/constant/dictType.js";

const loading = ref(true);
const saveLoading = ref(false);
const tableData = ref([]);
const pageNo = ref(1);
const pageSize = ref(10);
const total = ref(0);
const updateUserOpen = ref(false);
const resetPwdOpen = ref(false);
const drawerOpen = ref(false);
const searchUser = ref({
  username: "",
  phone: "",
  status: null,
});
const user = ref({});
//重置密码
const resetUserPwd = ref({
  id: null,
  password: "",
});
const tempUserName = ref("");
const checkedRoles = ref([]);
const allRoles = ref([]);
const statusData = ref([]);

onMounted(() => {
  getUserList();
  getAllRoleList();
  getDictTypeStatus();
});

//查询所有用户数据
const getUserList = () => {
  loading.value = true;
  findUserList(pageNo.value, pageSize.value, searchUser.value).then((res) => {
    if (res.code === 200 && res.data !== null) {
      tableData.value = res.data.data;
      total.value = res.data.total;
      loading.value = false;
    } else {
      loading.value = false;
    }
  });
};

//监听分页变化
const handlePaginationChange = (current, page) => {
  pageNo.value = current;
  pageSize.value = page;
  getUserList();
};

//查询字典状态
const getDictTypeStatus = () => {
  queryDictLabel(USER_CONSTANT).then((res) => {
    if (res.code === 200) {
      statusData.value = res.data;
    }
  });
};

//查询所有角色数据
const getAllRoleList = () => {
  queryRoleNameList().then((res) => {
    if (res.code === 200) {
      allRoles.value = res.data;
    }
  });
};

//重置
const handleReset = () => {
  searchUser.value = {
    username: "",
    phone: "",
    status: null,
  };
  getUserList();
};

//查询
const handleSearch = () => {
  if (
    searchUser.value.username !== "" ||
    searchUser.value.phone !== "" ||
    searchUser.value.status !== null
  ) {
    saveLoading.value = true;
    getUserList();
    saveLoading.value = false;
  }
};

//取消修改用户弹框
const handlerCancel = () => {
  updateUserOpen.value = false;
  resetPwdOpen.value = false;
  resetUserPwd.value = {
    id: null,
    password: "",
  };
};

//修改用户状态
const handleChangeStatus = (id) => {
  updateUserStatus(id).then((res) => {
    if (res.code === 200) {
      message.success("用户状态已修改！");
    }
  });
};

//用户数据回显
const handleEchoUser = (id) => {
  queryEchoUserInfo(id).then((res) => {
    if (res.code === 200) {
      user.value = res.data;
      updateUserOpen.value = true;
    }
  });
};

//修改用户
const handleSaveUser = () => {
  formRef.value.validate().then(() => {
    saveLoading.value = true;
    updateUserInfo(user.value).then((res) => {
      if (res.code === 200) {
        message.success("修改成功");
        updateUserOpen.value = false;
        saveLoading.value = false;
        getUserList();
      } else {
        saveLoading.value = false;
      }
    });
  });
};

//删除用户
const handleRemoveUser = (id) => {
  deleteUser(id).then((res) => {
    if (res.code === 200) {
      message.success("删除成功");
      getUserList();
    }
  });
};

//重置密码
const handleResetPwdOpen = (id) => {
  resetUserPwd.value.id = id;
  resetPwdOpen.value = true;
};

//重置密码
const handleResetPwd = (id) => {
  formRef.value.validate().then(() => {
    saveLoading.value = true;
    resetPwd(resetUserPwd.value).then((res) => {
      if (res.code === 200) {
        message.success("密码重置成功！");
        resetPwdOpen.value = false;
        saveLoading.value = false;
        resetUserPwd.value = {};
      } else {
        saveLoading.value = false;
      }
    });
  });
};

const onClose = () => {
  drawerOpen.value = false;
  tempUserName.value = "";
};

//分配角色抽屉
const handleRoleOpen = (item) => {
  tempUserName.value = item.username;
  saveLoading.value = true;
  queryRoles(item.id).then((res) => {
    if (res.code === 200) {
      checkedRoles.value = res.data;
      saveLoading.value = false;
      drawerOpen.value = true;
    } else {
      saveLoading.value = false;
    }
  });
};

//分配角色
const handleRoleSave = () => {
  saveLoading.value = true;
  saveRoles(tempUserName.value, checkedRoles.value).then((res) => {
    if (res.code === 200) {
      saveLoading.value = false;
      message.success("分配角色成功");
      drawerOpen.value = false;
      checkedRoles.value = [];
    } else {
      saveLoading.value = false;
    }
  });
};

const labelCol = {
  span: 6,
};
const wrapperCol = {
  span: 16,
};

const formRef = ref();
const rules = ref({
  username: [
    {
      required: true,
      message: "请输入用户名称",
      trigger: "change",
    },
  ],
  phone: [
    {
      required: true,
      message: "请输入手机号",
      trigger: "change",
    },
  ],
  email: [
    {
      required: true,
      message: "请输入邮箱",
      trigger: "change",
    },
  ],
  password: [
    {
      required: true,
      message: "请输入新密码",
      trigger: "change",
    },
  ],
});
</script>
<style scoped lang='scss'>
.permisson-role {
  height: 80px;
  width: 100%;
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.a-row-search {
  height: 100px;
  width: 85%;
  display: flex;
  align-items: center;
}

.pagination-style {
  height: 120px;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>